package com.kirk.cts.ui.view.panel;

import com.kirk.cts.core.constants.SystemConstants;
import com.kirk.cts.core.loader.ImageLoader;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.awt.*;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * <p> AdvertisementPanel.java </p>
 *
 * @version 1.0.0
 * @Author kirkliu
 * @Date 2020-09-01 23:19
 * @Description 广告
 */
@Component("advertisementPanel")
public class AdvertisementPanel extends JPanel {
    private static final long serialVersionUID = 1L;
    private JPanel containerPanel;
    private String currImagePath;

    public AdvertisementPanel() {
        super();
        init();
    }

    private void init() {
        FlowLayout layout = new FlowLayout(FlowLayout.LEFT, 0, 0);
        this.setLayout(layout);
        containerPanel = new JPanel();
        this.add(containerPanel);
        repaintImage();
    }

    public void setImagePath(String imagePath) {
        this.currImagePath = imagePath;
        repaintImage();
    }

    public String getImagePath() {
        return this.currImagePath;
    }

    private void repaintImage() {
        try {
            containerPanel.removeAll();
            ImageIcon tempImage = null;
            if (StringUtils.isBlank(this.currImagePath)) {
                tempImage = ImageLoader.getImageIcon("CrawlerResource.defaultAd");
            } else {
                if (this.currImagePath.startsWith(SystemConstants.HTTP) || this.currImagePath.startsWith(SystemConstants.HTTPS)) {
                    tempImage = new ImageIcon(new URL(this.currImagePath));
                } else {
                    tempImage = new ImageIcon(this.currImagePath);
                }
            }
            final ImageIcon image = tempImage;
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    containerPanel.add(new JLabel(image));
                    containerPanel.repaint();
                    containerPanel.doLayout();
                }
            });
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

}
